<?php

namespace App;

use App\Model\BankCard;
use App\Model\CardHolder;
use App\Model\Cards;
use App\Model\InterPushMatchUser;
use App\Model\InterPushUserInfo;
use App\Model\Operators;
use App\Model\Partner;
use App\Model\Salesmen;
use App\Model\UserBonusCount;
use App\Model\UserBonusTurnWalletLog;
use App\Model\UserCommissionDetail;
use App\Model\UserDetail;
use App\Model\UserFrom;
use App\Model\UserGrade;
use App\Model\UserInterPushInfo;
use App\Model\UserInterPushRecord;
use App\Model\UserInviteOneYuan;
use App\Model\UserMarketing;
use App\Model\UserRecharge;
use App\Model\UserSalesmanBonusCount;
use App\Model\UserSalesmanInviteOneYuan;
use App\Model\UserWalletRecordLog;
use App\Model\VipFeeConfig;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\JWTSubject;

/**
 * Class User
 *
 * @package App
 * @method static \Illuminate\Database\Query\Builder|User where($column, $operator = null, $value = null, $boolean = 'and')
 * @method static \Illuminate\Database\Query\Builder|User find($id, $columns = ['*'])
 * @method static \Illuminate\Database\Query\Builder|User first($columns = ['*'])
 * @property-read \App\Model\BankCard $bankCard
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\CardHolder[] $cardHolders
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\InterPushMatchUser[] $interPushMatchUser
 * @property-read \App\Model\InterPushUserInfo $interPushUserInfo
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @property-read \App\Model\Operators $operators
 * @property-read \App\Model\Partner $partner
 * @property-read \App\Model\Salesmen $salesmen
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserCommissionDetail[] $userCommissionDetails
 * @property-read \App\Model\UserFrom $userFrom
 * @property-read \App\Model\UserGrade $userGrade
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserMarketing[] $userMarketing
 * @property-read \App\Model\UserRecharge $userRecharges
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User query()
 * @property int $id
 * @property int|null $type 用户类型:0管理员1城市合伙人2运营3业务4会员
 * @property int $pid 上级id，只允许城市id和会员id
 * @property int $salesman_id 业务员id
 * @property int $operator_id 运营商id
 * @property int $place_partner_id 城市合伙人id
 * @property int|null $enterprise_user_id 关联企业id，用于企业返佣
 * @property int $is_fase_distribution 是否是虚拟账号，1是，0不是
 * @property int $is_change_grade 是否由业务员变为会员,0可以改变，1不能改变
 * @property string|null $account 账号
 * @property string $phone 电话号码
 * @property string|null $password 密码
 * @property string|null $email email
 * @property float|null $money 总金额
 * @property float $maibao 脉宝
 * @property float $maibao_real 没有通过经销商的脉宝
 * @property float $maibao_all 累计脉宝
 * @property float $custom_income 个人网页收入
 * @property string|null $payment_password 支付密码
 * @property float|null $availableAmount 可提金额
 * @property float|null $freezingAmount 冻结金额
 * @property int|null $is_enabled 是否启用 0启用 1禁用
 * @property string|null $enabled_at 封停开启时间
 * @property string $logged_ip ip
 * @property string|null $logged_at 最后登录时间
 * @property float $agency_fee 代理费
 * @property float|null $currentCommission 当前可以佣金
 * @property float $rewards_all 奖励金总计(只增不减)
 * @property float|null $changeCommission 累计转余额的佣金
 * @property string|null $qr_code 用户生成二维码地址
 * @property int|null $from_type 通过活动进入类型1普通活动， 2特殊活动
 * @property \Illuminate\Support\Carbon|null $created_at 创建时间
 * @property \Illuminate\Support\Carbon|null $updated_at 修改时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereAccount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereAgencyFee($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereAvailableAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereChangeCommission($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereCurrentCommission($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereCustomIncome($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereEnabledAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereEnterpriseUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereFreezingAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereFromType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereInvitationCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereIsChangeGrade($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereIsEnabled($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereIsFaseDistribution($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereLoggedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereLoggedIp($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereMaibao($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereMaibaoAll($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereMaibaoReal($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereOperatorId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User wherePaymentPassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User wherePhone($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User wherePid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User wherePlacePartnerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereQrCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereRewardsAll($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereSalesmanId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereUpdatedAt($value)
 * @property float|null $current_commission 会员当前可以佣金
 * @property float|null $change_commission 会员累计转余额的佣金
 * @property float|null $salesman_current_commission 业务员当前可以佣金
 * @property float|null $salesman_change_commission 业务员累计转余额的佣金
 * @property float $salesman_rewards_all 业务员奖励金总计(只增不减)
 * @property string|null $invitation_code 邀请码
 * @property-read \App\Model\Cards $cards
 * @property-read \App\Model\UserDetail $detail
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereSalesmanChangeCommission($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereSalesmanCurrentCommission($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereSalesmanRewardsAll($value)
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserBonusCount[] $bonusCount
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserBonusTurnWalletLog[] $bonusTurnWalletLog
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserSalesmanInviteOneYuan[] $salesmanBonusCount
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserWalletRecordLog[] $walletRecordLog
 * @property string|null $register_source wechat 公众号， app。注册来源
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserInviteOneYuan[] $inviteOneYuan
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserSalesmanInviteOneYuan[] $salesmanInviteOneYuan
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereRegisterSource($value)
 * @property-read \App\Model\UserInterPushInfo $interPushInfo
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserInterPushRecord[] $interPushRecord
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\UserInterPushRecord[] $passiveInterPushRecord
 */
class User extends Authenticatable implements JWTSubject
{
    protected $table = 'users';

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'account', 'email', 'password', 'phone',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password'
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 获取用户详情（会员，业务员）
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function detail()
    {
        return $this->hasOne(UserDetail::class, 'user_id', 'id');
    }

    /**
     * 业务员信息
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function salesmen()
    {
        return $this->hasOne(Salesmen::class, 'user_id', 'id');
    }


    public function partner()
    {
        return $this->hasOne(Partner::class, 'user_id', 'id');
    }

    public function operators()
    {
        return $this->hasOne(Operators::class, 'user_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function cards()
    {
        return $this->hasOne(Cards::class, 'user_id', 'id');
    }

    public function cardHolders()
    {
        return $this->hasMany(CardHolder::class, 'user_id', 'id');

    }
    public function bankCard()
    {
        return $this->hasOne(BankCard::class, 'user_id', 'id');
    }

    public function userFrom()
    {
        return $this->hasOne(UserFrom::class, 'user_id', 'id');
    }

    public function userRecharges()
    {
        return $this->hasOne(UserRecharge::class, 'user_id', 'id');
    }

    /**
     * 获取用户的充值会员类型
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function userGrade()
    {
        return $this->hasOne(UserGrade::class, 'user_id', 'id');
    }

    /**
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userCommissionDetails()
    {
        return $this->hasMany(UserCommissionDetail::class, 'user_id', 'id');
    }

    // 获取用户间接推广用户
    public function getUserFromIndirectpPromUser($user_id)
    {
        return User::whereIn('id', function ($query) use ($user_id) {
            $query->select('user_id')->from('user_from')->where('two_user_id', $user_id);
        })->get();
    }

    // 获取用户直接推广用户
    public function getUserFrom($relation_id, $relation ,  $type)
    {
        switch ($relation){
            case 4:
                if ($type == 1){
                    return UserFrom::where(['one_user_id'=>  $relation_id])->get();
                }else{
                    return UserFrom::where(['tow_user_id'=>  $relation_id])->get();
                }
                break;
            case 3:
                if ($type == 1){
                    return UserFrom::where(['one_salesman_id'=>  $relation_id])->get();
                }elseif ($type == 2){
                    return UserFrom::where(['two_salesman_id'=>  $relation_id])->get();
                }else{
                    return UserFrom::where(['three_salesman_id'=>  $relation_id])->get();
                }
                break;
        }

        return '';
    }

    public function getUserFromAmount($relation_id, $relation ,  $type)
    {
        switch ($relation){
            case 4:
                return UserCommissionDetail::where(['relation_id'=>  $relation_id, 'relation' => $type])->get();
                break;
            case 3:
                if ($type == 1){
                    return UserCommissionDetail::where(['relation_id'=>  $relation_id, 'relation' => 3])->get();
                }elseif ($type == 2){
                    return UserCommissionDetail::where(['relation_id'=>  $relation_id, 'relation' => 4])->get();
                }else{
                    return UserCommissionDetail::where(['relation_id'=>  $relation_id, 'relation' => 5])->get();
                }
                break;
        }

        return '';
    }

    public static function getUserName($id)
    {
        $name = Cards::where('user_id', $id)->first();
        if ($name && $name->user_name){
            return $name->user_name;
        }else{
              $user_detail = UserDetail::where('user_id', $id)->first();
              return isset($user_detail->wechat_name) ? $user_detail->wechat_name : '';
        }
    }

    /**
     * 获取用户用户互推信息
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function interPushUserInfo()
    {
        return $this->hasOne(InterPushUserInfo::class, 'user_id', 'id');
    }

    /**
     * 获取用户互推圈主动推送用户
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function interPushMatchUser()
    {
        return $this->hasMany(InterPushMatchUser::class, 'user_id', 'id');
    }

    /**
     * todo 获取用户互推信息
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function interPushInfo()
    {
        return $this->hasOne(UserInterPushInfo::class, "user_id", "id");
    }

    // todo 用户分享记录


    /**
     * 获取用户营销网页
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userMarketing()
    {
        return $this->hasMany(UserMarketing::class, "user_id", "id");
    }

    public static function VipLevel()
    {
        $user = Auth::user();
        if (empty($user)){
            return 0;
        }
        return self::is_vip($user->id)?:0;
    }

    public static function is_vip($user_id)
    {
        $grade = DB::table('user_grade')->where('user_id', $user_id)->where('overed_at', '>', Carbon::now())->get();
        $users = $grade->pluck('user_id');
        if (in_array($user_id, $users->toArray())){
            $vip = VipFeeConfig::whereIn('id', $grade->pluck('vip_fee_config_id'))->first();
            if ($vip){
                return $vip->type;
            }
        }
        return false;
    }


    /**
     * 会员一元拉新
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function inviteOneYuan()
    {
        return $this->hasMany(UserInviteOneYuan::class, "user_id", "id");
    }

    /**
     * 业务员一元拉新
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function salesmanInviteOneYuan()
    {
        return $this->hasMany(UserSalesmanInviteOneYuan::class, "user_id","id");
    }


    /**
     * 获取会员奖励金记总录表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function bonusCount()
    {
        return $this->hasMany(UserBonusCount::class,"user_id", "id");
    }

    /**
     *  获取业务员奖励金记总录表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function salesmanBonusCount()
    {
        return $this->hasMany(UserSalesmanBonusCount::class, "user_id", "id");
    }

    /**
     * 获取会员对应的奖励金转入钱包记录表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function bonusTurnWalletLog()
    {
        return $this->hasMany(UserBonusTurnWalletLog::class, "user_id", "id");
    }

    /**
     *  获取会员钱包记录总表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function walletRecordLog()
    {
        return $this->hasMany(UserWalletRecordLog::class, "user_id", "id");
    }

    public function name()
    {
        $detail = UserDetail::where('user_id', $this->id)->first();
        $card = Cards::where('user_id', $this->id)->first();
        if ($card && $card->user_name) {
            return $card->user_name;
        }
        return $detail?$detail->wechat_name:'';
    }
    public function portrait()
    {
        $detail = UserDetail::where('user_id', $this->id)->first();
        $card = Cards::where('user_id', $this->id)->first();
        if ($card && $card->head_picture) {
            return $card->head_picture;
        }
        return $detail?$detail->head_portrait:'';
    }

}
